package cqrtplm.controller.thirdPartyAPI;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.pdm.ec.module.vo.ChgFormVO;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowChgFormView;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowObject;
import com.hustcad.plm.pdm.flowbusiness.model.entity.WorkFlowObjectPackage;
import com.hustcad.plm.pdm.form.model.vo.TyplmFormDataVO;
import com.hustcad.plm.pdm.form.service.TyFormDataExtService;
import com.hustcad.plm.pdm.util.RedisUtils;
import com.hustcad.plm.pdm.workflow.model.entity.WorkFlowContainerView;
import com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowContainerService;
import com.lark.oapi.okhttp.OkHttpClient;
import com.lark.oapi.okhttp.Request;
import com.lark.oapi.okhttp.Response;
import com.ty.basic.response.ResponseResult;
import com.ty.basic.session.TyAccountContext;
import cqrtplm.mapper.OaApiMapper;
import cqrtplm.service.OaApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Locale;


@RestController
@RequestMapping("/rest/oaApi/v1")
@Slf4j
public class OaApiController {

    @Resource
    private OaApiService oaApiService;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private OaApiMapper oaApiMapper;

    @Resource
    private TyplmWorkFlowContainerService typlmWorkFlowContainerService;
    @Resource
    private TyFormDataExtService tyFormDataExtService;

    @Value("${oa.changeInfo.url}")
    private String url;
    @Autowired
    private RedisUtils redisUtils;

    //暂停
    @PostMapping("/parseFormData")
    public ResponseResult parseFormData(@RequestBody String jsonString){
        log.info(">>>OaApiController>>>>>parseFormData>>>>{}",jsonString);
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        //项目恢复
        String field0060 = jsonObject.getString("field0060");
        //项目暂停
        String field0012 = jsonObject.getString("field0012");
        //开发计划
        String field0011 = jsonObject.getString("field0011");

        String type=null;
        if (StrUtil.isBlank(field0060) && StrUtil.isBlank(field0012) && StrUtil.isBlank(field0011)) {
            return ResponseResult.fail("400","未选择变更类型");
        }else if (StrUtil.isNotBlank(field0060) && field0060.equals("1") && StrUtil.isNotBlank(field0012) && field0012.equals("1")) {
            return ResponseResult.fail("400","变更类型不能多选");
        }else {

            if (StrUtil.isNotBlank(field0060) && field0060.equals("1")) {
                type="项目恢复";
            }else if (StrUtil.isNotBlank(field0012) && field0012.equals("1")) {
                type="项目暂停";
            }else if (StrUtil.isNotBlank(field0011) && field0011.equals("1")) {
                type="开发计划";
            }else {
                type="其他";
            }
        }
        String projectId=oaApiService.selectProjectIdByName(jsonObject.getString("field0003"));
        if (StrUtil.isBlank(projectId)){
            return ResponseResult.fail("400","项目名称有误");
        }
        // 构建请求头
        org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
        // 设置认证令牌
        headers.set(org.springframework.http.HttpHeaders.AUTHORIZATION, TyAccountContext.getToken());
        JSONObject js = new JSONObject();
        js.put("oid",projectId);
        HttpEntity<String> requestEntity = new HttpEntity<>(js.toJSONString(), headers);
        // 设置内容类型为JSON
        headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);

        if (type.equals("项目暂停")) {

            ResponseEntity<String> exchange = restTemplate.exchange("http://127.0.0.1:9588/api/v1/oaApi/pause",
                                                                    HttpMethod.POST,
                                                                    requestEntity,
                                                                    String.class);
            String body = exchange.getBody();
            JSONObject json= JSONObject.parseObject(body);
            String r = json.getString("result");
            if (StrUtil.isBlank(r)&&r==null){
                return ResponseResult.fail("400",json.getString("message"));
            } else if (StrUtil.isBlank(r)) {
                return ResponseResult.fail("400",r);
            }

            if (r.equals("SUCCESS")){
                return ResponseResult.success(body);
            }else {
                return ResponseResult.fail("400",json.getString("message"));
            }
        }else if (type.equals("项目恢复")){
            ResponseEntity<String> exchange = restTemplate.exchange("http://127.0.0.1:9588/api/v1/oaApi/restart",
                                                                    HttpMethod.POST,
                                                                    requestEntity,
                                                                    String.class);
            String body = exchange.getBody();
            JSONObject json= JSONObject.parseObject(body);
            String r = json.getString("result");
            if (StrUtil.isBlank(r)&&r==null){
                return ResponseResult.fail("400",json.getString("message"));
            } else if (StrUtil.isBlank(r)) {
                return ResponseResult.fail("400",r);
            }
            if (r.equals("SUCCESS")){
//                JSONArray names = jsonObject.getJSONArray("field0045");
//                JSONArray startTimes = jsonObject.getJSONArray("field0041");
//                JSONArray finishTimes = jsonObject.getJSONArray("field0042");
//                String str = jsonObject.getString("field0032");
//                String[] split = str.substring(str.indexOf(":") + 2).split(",");
//                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
//                JSONArray jsonArray=new JSONArray();
//                for (int i = 0; i < names.size(); i++) {
//                    JSONObject obj=new JSONObject();
////                    String oid=oaApiMapper.selectPlan(names.getString(i).replaceAll("\\s+", ""),projectId,split[i]);
//                    String oid=split[i];
//                    LocalDateTime st = java.time.ZonedDateTime
//                            .parse(startTimes.getString(i).trim(), formatter)
//                            .withZoneSameInstant(ZoneId.systemDefault()) // 转换为系统时区
//                            .toLocalDateTime();
//                    LocalDateTime et = java.time.ZonedDateTime
//                            .parse(finishTimes.getString(i).trim(), formatter)
//                            .withZoneSameInstant(ZoneId.systemDefault()) // 转换为系统时区
//                            .toLocalDateTime();
//                    obj.put("planId",oid);
//                    obj.put("startDate",st);
//                    obj.put("finishDate",et);
//                    obj.put("name",names.getString(i).replaceAll("\\s+", ""));
//                    jsonArray.add(obj);
//                }
//                oaApiService.updatePlanActivity(jsonArray);
                return ResponseResult.success(body);
            }else {
                return ResponseResult.fail("400",json.getString("message"));
            }

        }else if (type.equals("开发计划")){
            JSONArray names = jsonObject.getJSONArray("field0045");
            JSONArray startTimes = jsonObject.getJSONArray("field0041");
            JSONArray finishTimes = jsonObject.getJSONArray("field0042");
            String str = jsonObject.getString("field0032");
            if (str.contains("修改计划时间")){
                String[] split = str.substring(str.indexOf(":") + 1).split(",");
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
                JSONArray jsonArray=new JSONArray();
                for (int i = 0; i < names.size(); i++) {
                    JSONObject obj=new JSONObject();
                    //                String oid=oaApiMapper.selectPlan(names.getString(i).replaceAll("\\s+", ""),projectId,split[i]);
                    String oid=split[i];
                    LocalDateTime st = java.time.ZonedDateTime
                            .parse(startTimes.getString(i).trim(), formatter)
                            .withZoneSameInstant(ZoneId.systemDefault()) // 转换为系统时区
                            .toLocalDateTime();
                    LocalDateTime et = java.time.ZonedDateTime
                            .parse(finishTimes.getString(i).trim(), formatter)
                            .withZoneSameInstant(ZoneId.systemDefault()) // 转换为系统时区
                            .toLocalDateTime();
                    obj.put("planId",oid);
                    obj.put("startDate",st);
                    obj.put("finishDate",et);
                    obj.put("name",names.getString(i).replaceAll("\\s+", ""));
                    jsonArray.add(obj);
                }
                log.info("远程调用PPM参数："+jsonArray.toJSONString());
                String body = oaApiService.updatePlanActivity(jsonArray);
                JSONObject json= JSONObject.parseObject(body);
                String r = json.getString("result");
                if (StrUtil.isBlank(r)&&r==null){
                    return ResponseResult.fail("400",json.getString("message"));
                } else if (StrUtil.isBlank(r)) {
                    return ResponseResult.fail("400",r);
                }else if (r.equals("ERROR")) {
                    String string = json.getJSONObject("errors").getString("message");
                    return ResponseResult.fail("400",string);
                }
                return ResponseResult.success();
            }else if (str.contains("对象")){
                String key = str.substring(str.indexOf(":")+1, str.indexOf("新"));
                JSONObject obj=new JSONObject();
                obj.put("projectId",projectId);
                obj.put("key",key);
                HttpEntity<String> request = new HttpEntity<>(obj.toJSONString(), headers);
                ResponseEntity<String> exchange = restTemplate.exchange("http://127.0.0.1:9588/api/v1/oaApi/updatePlanActivity",
                                                                        HttpMethod.POST,
                                                                        request,
                                                                        String.class);
                String body = exchange.getBody();
                JSONObject json= JSONObject.parseObject(body);
                String r = json.getString("result");
                if (StrUtil.isBlank(r)&&r==null){
                    return ResponseResult.fail("400",json.getString("message"));
                } else if (StrUtil.isBlank(r)) {
                    return ResponseResult.fail("400",r);
                }else if (r.equals("ERROR")) {
                    String string = json.getJSONObject("errors").getString("message");
                    return ResponseResult.fail("400",string);
                }
                return ResponseResult.success();
            }
        }
       return ResponseResult.fail("400","错误的变更类型！");


    }

    @PostMapping("/processAwakenedOA")
    public ResponseResult processAwakenedOA(@RequestBody JSONObject jsonObject){
        try {
            String workFlowContainerId = jsonObject.getString("workFlowContainerOid");
            String btnName = jsonObject.getString("btnName");
            WorkFlowContainerView workFlowContainerView = typlmWorkFlowContainerService.getWorkFlowContainerDetailByPrimaryKey(
                    new BigInteger(workFlowContainerId));
            if (workFlowContainerView.getWorkFlowName().equals("修模变更通知流程")){
                if(workFlowContainerView instanceof FlowChgFormView) {
//                    log.info("当前流程属于变更流程");
                    FlowChgFormView flowChgFormView = (FlowChgFormView) workFlowContainerView;
//                    List<FlowTaskRecord> flowTaskRecordList = workFlowObjectPackage.getFlowTaskRecordList();
//                    FlowTaskRecord flowTaskRecord = flowTaskRecordList.get(flowTaskRecordList.size() - 1);
//                    if (flowTaskRecord.getTaskName().equals("测试")){
                    ChgFormVO chgFormVO = flowChgFormView.getChgFormVO();
                    String changeNo=chgFormVO.getObjectNumber();
                    if (changeNo.contains("RTTJXM")){
                        if (btnName.equals("填写报销单")){
                            String formData = chgFormVO.getFormData();
                            JSONObject json = JSONObject.parseObject(formData);
                            JSONObject testObj = json.getJSONObject("testObj");
                            String string = testObj.getString("batchProduction");
                            if (StrUtil.isNotBlank(string)){
                                if(string.equals("量产前")){
                                    JSONObject js = buildOAFormData("reimbursement");
                                    String oaUrl = getOAUrl(js);
                                    return ResponseResult.success(oaUrl);
                                }else if (string.equals("量产后")){
                                    JSONObject js = buildOAFormData("DevelopmentExpense");
                                    String oaUrl = getOAUrl(js);
                                    return ResponseResult.success(oaUrl);
                                }
                            }
                        }
                    }
                }
            }
            return ResponseResult.success();
        }catch (Exception e){
            return ResponseResult.success();
        }

    }


    public JSONObject buildOAFormData(String FormCode){
        JSONObject data = new JSONObject();
        data.put("templeteNumber",FormCode);
        data.put("loginName","22051030");
        return data;
    }

    public String getOAUrl(JSONObject jsonObj){
        String str = jsonObj.toJSONString();
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        com.lark.oapi.okhttp.MediaType mediaType = com.lark.oapi.okhttp.MediaType.parse("application/json");
        com.lark.oapi.okhttp.RequestBody body = com.lark.oapi.okhttp.RequestBody.create(mediaType, str);
        Request request = new Request.Builder()
                .url(this.url)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();

        try {
            //            String str = URLEncoder.encode(data.toJSONString(), "UTF-8");
            Response response = client.newCall(request).execute();
            String json = response.body().string();
            if(StrUtil.isNotBlank(json)){
                JSONObject jsonObject = JSONObject.parseObject(json);
                if (jsonObject.getString("success").equals("true")){
                    return jsonObject.getString("url");
                }
            }
            return null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }



    //项目恢复启动接口
//    @PostMapping("/restart")
//    public ResponseResult<String> restart(@RequestBody String jsonString) {
//        JSONObject jsonObject = JSONObject.parseObject(jsonString);
//        String projectId=oaApiService.selectProjectIdByName(jsonObject.getString("field0003"));
//        if (StrUtil.isBlank(projectId)){
//            return ResponseResult.fail("400","项目名称有误");
//        }
//        // 构建请求头
//        org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
//        // 设置认证令牌
//        headers.set(org.springframework.http.HttpHeaders.AUTHORIZATION, TyAccountContext.getToken());
//
//        JSONArray arr = new JSONArray();
//        arr.add("738453819676950528");
//        JSONObject js = new JSONObject();
//        js.put("input",arr);
//        HttpEntity<String> requestEntity = new HttpEntity<>(js.toJSONString(), headers);
//        // 设置内容类型为JSON
//        headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
//        ResponseEntity<String> exchange = restTemplate.exchange("http://127.0.0.1:7002/typrjmng/api/v1/project/setProjectStateRecovery",
//                                                                HttpMethod.POST,
//                                                                requestEntity,
//                                                                String.class);
//
//        String body = exchange.getBody();
//        JSONObject json= JSONObject.parseObject(body);
//        String r = json.getString("result");
//        if (r.equals("SUCCESS")){
//            return ResponseResult.success(body);
//        }else {
//            return ResponseResult.fail("400",json.getString("message"));
//        }
//    }
}
